package com.happy.study.servier.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.happy.study.dao.QuestionMapper;
import com.happy.study.entity.QuestionEntity;
import com.happy.study.servier.IQuestionService;
import com.happy.study.util.StateEnum;
import com.happy.study.util.StateException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, QuestionEntity> implements IQuestionService {

    @Resource
    private QuestionMapper questionMapper;

    @Override
    public List<QuestionEntity> queryList ( QuestionEntity questionEntity ) {
        if ( questionEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        List<QuestionEntity> questionEntities = questionMapper.queryList ( questionEntity.getTitle (), questionEntity.getCategoryId(), ( questionEntity.getPageNum () - 1 ) * questionEntity.getPageSize (), questionEntity.getPageSize () );
        return questionEntities;
    }


    /**
     * 保存问题或文章，副标题为空则取主标题
     *
     * @param questionEntity
     * @return
     */
    @Override
    public QuestionEntity addSingle ( QuestionEntity questionEntity ) {
        if ( questionEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        if ( questionEntity.getSubTitle () == null || "".equals ( questionEntity.getSubTitle () ) ) {
            questionEntity.setSubTitle ( questionEntity.getTitle () );
        }
        questionEntity.setCreateTime ( new Date () );
        int insert = baseMapper.insert ( questionEntity );
        if ( insert == 0 ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return questionEntity;
    }

    /**
     * 根据问题或文章Id查询信息
     *
     * @param id
     * @return
     */
    @Override
    public QuestionEntity querySingle ( int id ) {
        if ( id == 0 ) {
            throw new StateException ( StateEnum.PRIMARY_NULL_EXCE );
        }
        QuestionEntity questionEntity = questionMapper.querySingle ( id );
        return questionEntity;
    }
}
